// pages/index/index.js
const common = require('../../../public.js')
// const amap = require('../../libs/amap-wx')
const QQMapWX = require('../../../libs/qqmap-wx-jssdk1.2/qqmap-wx-jssdk')
const app = getApp()
const utils = require('./utils.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabs: 'managerId',
    laba: false,
    toptwo: 0,
    showAd: true, // 是否显示广告组件
    bannerList: [], // 上方轮播图的数据
    pageNum: 0,
    benefitListData: [], // 推荐商家列表
    token: '',
    city: '', // 获取城市
    lon: '',
    lat: '',
    refreshing: false, // 标记是否正在刷新数据
    isLoadingBusy: false, // 标记是否正在加载更多数据
    isMore: true, // 标记是否还有更多数据
    height: '', //胶囊位置
    top: '', //胶囊位置
    currentItemId: 2,
    tourList: [], //游景区
    tourList1: [], //品美食
    tourList2: [],
    tourList3: [],
    tourList4: [],
    bann_ner: [],
    gong: [],
    tabs: "managerId",
    regionId: '',
    swiperCurrent: 0,
    current: 0,
    circular: true,
    vertical: false,
    autoplay: true,
    interval: 3000,
    duration: 1500,
    dots: true,
    indicatorDots: true,
    autoplay: false, // 自动播放
    interval: 5000, //轮播时间
    duration: 300, // 滑动速度越大越慢
    circular: true, //是否循环
    beforeColor: "lightgray", //指示点颜色
    afterColor: "red", //当前选中的指示点颜色
    // 轮播数据 + 效果 E
    controls: true,
    plays: true,
    regionIdFlag: '', //判断是不是区
    versionNum: 1,
    indexs: 0,
    currentIndex: 0,
    fuckList: [],
    weather: [], //天气预报
    regionName: '',
    managerId: '',
  },
  fuck_two(e) {
    let item = e.currentTarget.dataset.item
    if (item.redirectUrl) {
      wx.navigateTo({
        url: '/packageA/pages/Goods/details/index?id=' + item.redirectUrl
      })
    } else if (item.redirectPath) {
      wx.navigateTo({
        url: '/packageA/pages/Goods/details/index?id=' + item.redirectPath
      })
    } else {
      wx.navigateTo({
        url: item.redirectPath,
      })
    }
  },
  fuckLis(e) { },
  // 附近场馆接口
  Venue() {
    var that = this
    let tempJson = {
      storeTypeId: 23,
      regionName: this.data.regionName,
      cityName: this.data.city,
      pageNum: 1,
      pageSize: 9,
      xpoint: this.data.lon,
      ypoint: this.data.lat,
      distance: '',
      recentIncome: '',
      commentRate: '',
      Index: 0
    }
    common.post('/store/getSearchStoreListByStoreTypeId', tempJson, function (res) {
      if (res.status === 200) {
        //  res.data = res.data.splice(1)
        for (var i = 0; i < res.data.length; i++) {
          res.data[i].distance = parseFloat(res.data[i].distance / 1000).toFixed(1)
        }
        // 第一步 先设置数组前三个比较
        var min = res.data[0].distance
        for (var i = 1; i < 2; i++) {
          var cur = res.data[i].distance
          // 小于等于
          if (cur < min) {
            min = cur
            res.data[i]['aa'] = true
            var obj = {}
            obj = res.data[0]
            res.data[0] = res.data[i]
            res.data[i] = obj
          } else {
            res.data[0]['aa'] = true
          }

          that.setData({
            VenueList: res.data
          })

        }

      }
    })
  },
  // 附近场馆计算最短距离
  handleChanges(e) {
    var that = this
    // 三位比较大小
    var Index = e.detail.current //轮播图的第一位
    that.setData({
      Index
    }, () => {
      var arr = that.data.VenueList.slice(that.data.Index, that.data.Index + 3)
      if (arr.length == 0) {
        arr.push(that.data.VenueList[0], that.data.VenueList[1], that.data.VenueList[2])
      } else if (arr.length == 1) {
        arr.push(that.data.VenueList[0], that.data.VenueList[1],)
      } else if (arr.length == 2) {
        arr.push(that.data.VenueList[0])
      }
      var min = arr[0].distance
      var id = 0
      var smallIndex = 0 //小数组里面的下标
      for (var j = 0; j < arr.length; j++) {
        var cur = parseFloat(arr[j].distance)
        if (cur <= min) {
          min = cur
          smallIndex = j
          id = arr[j].id

        }
      }

      var bigIndex = 0
      for (var i = 0; i < that.data.VenueList.length; i++) {
        if (id == that.data.VenueList[i].id) {
          that.data.VenueList[i]['aa'] = true
          bigIndex = i
          var obj = {}
          obj = that.data.VenueList[i]
          that.data.VenueList[i] = that.data.VenueList[Index]
          that.data.VenueList[Index] = obj
        } else {
          that.data.VenueList[i]['aa'] = false
        }
      }
      that.setData({
        VenueList: that.data.VenueList
      }, () => { })

    })
  },
  // 跳转会员卡
  go_card(e) {
    console.log(e, "55555")
    let item = e.currentTarget.dataset.item
    if (item.redirectUrl) {
      wx.navigateTo({
        // url: item.redirectUrl,
        url: '/packageA/pages/Goods/details/index?id=' + item.redirectUrl
      })
    } else {
      wx.navigateTo({
        url: item.redirectPath,
      })
    }
  },
  // 关闭声音
  click_labawu() {
    this.setData({
      laba: true
    })
  },
  click_typecategroy(e) {
    let {
      item
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/classification/classificationGoods/index?cid=' + item.cid,
    })
  },
  // 打开声音
  click_labay() {
    this.setData({
      laba: false
    })
  },
  // 播放
  videoPlay: function () {
    var videoplay = wx.createVideoContext("video");
    videoplay.play()
    this.setData({
      controls: false,
      plays: false
    })
  },
  //   暂停
  jieshu() {
    var videoplay = wx.createVideoContext("video");
    videoplay.stop()
    this.setData({
      controls: true,
      plays: true
    })
  },
  //   播放到结尾
  ended() {
    this.setData({
      controls: true,
      plays: true
    })
  },
  // 切换tabbar
  onChangeTabbars(e) { //切换底部导航
    console.log(e)
    const index = e.detail.index
    const url = e.detail.url + '?fl=lanling'
    if (index != this.data.active) {
      utils.onChangeTabbar(url, this.data.storeId, this.data.moduleType)
    }
  },
  swiperChanges(e) {
    var videoplay = wx.createVideoContext("video");
    videoplay.stop()
    this.setData({
      controls: true
    })
  },
  swiperChanges_two(e) {
    this.setData({
      indexs: e.detail.current
    })
  },
  click_in(e) {
    this.setData({
      toptwo: e.detail.scrollTop
    })
  },
  swiperChange: function (e) {
    var currentItemId = e.detail.currentItemId;
    this.setData({
      currentItemId: currentItemId
    })
  },
  //   跳转烟台
  click_coup() {
    if (this.data.regionIdFlag) {
      wx.navigateTo({
        url: '/pages/cultureCoupons/receiveCoupon/index?regionId=' + this.data.regionIdFlag,
      })
      return
    }
    wx.navigateTo({
      url: '/pages/cultureCoupons/receiveCoupon/index?cityId=' + this.data.regionId,
    })
  },
  onLoad: function (options) {
    var that = this
    var managerId = options.managerId ? options.managerId : ''
    if (managerId) {
      wx.setStorageSync('managerId', managerId)
    }
    this.setData({
      managerId: wx.getStorageSync('managerId'),
      // regionName
    })
  
    this.two_ad()
    this.mu_Ban()
    this.refresh()
    this.typeList() //首页游景区
    this.gong_Gao()
    this.adverList()

    // 胶囊位置
    let capsule = wx.getMenuButtonBoundingClientRect()
    this.setData({
      height: capsule.height,
      top: capsule.top,
    })
  },
  // 跳转景区
  toScenicArea(e) {
    let {
      id
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/ScenicArea/ScenicAreaMainPage/index?id=' + id + '&moduleType=' + this.data.type,
    })
  },
  // 景区推荐

  handleChange: function (e) {

    if (this.data.current == 0 && this.data.currentIndex > 1) { //卡死时，重置current为正确索引
      this.setData({
        current: this.data.currentIndex
      });
    } else { //正常轮转时，记录正确页码索引
      this.setData({
        currentIndex: e.detail.current
      });
    }

  },
  tour() {
    var that = this
    let tempJson = {
      storeTypeId: 6,
      regionName: this.data.regionName,
      cityName: this.data.city,
      pageNum: 1,
      pageSize: 10,
      xpoint: this.data.lon,
      ypoint: this.data.lat,
      distance: '',
      recentIncome: '',
      commentRate: '',
    }
    common.post('/store/getSearchStoreListByStoreTypeId', tempJson, function (res) {
      if (res.status === 200) {
        that.setData({
          tourList_two: res.data
        })
      }
    })
  },
  // 判断小程序模板
  mu_Ban() {
    var that = this
    var tempJson = {
      managerId: this.data.managerId,
    }
    common.getJson('/wlplatfrom/getStyleTypeForManager ', tempJson, res => {
      if (res.status === 200) {
        this.setData({
          versionNum: res.data
        })

      }
    })
  },
  onReady: function () {
    var that = this;
    var query = wx.createSelectorQuery()
    query.select('#lplistbd').boundingClientRect(function (res) { }).exec()
  },

  // 跳转
  gong_detailss(e) {
    let {
      id,
      title
    } = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/pages/Dj/gongDetail/gongDetail?id=' + id + '&name=' + title,
    })
  },
  refresh() {
    var that = this
    // 当前正在刷新，不需要再次获取数据
    if (this.data.refreshing === true) {
      return
    }
    this.setData({
      refreshing: true
    })
    this.getBannerInfo()
    this.getGoodsType()
    app.getLocation(
      (data) => {
        console.log(data,"真好的")
        var adcode = data.ad_info.adcode
        this.data.lon = data.longitude
        this.data.lat = data.latitude
        this.data.region = data.regeocodeData.addressComponent.district // 地区
        // this.data.city =  data.regeocodeData.addressComponent.district 

        this.setData({
          city:data.regeocodeData.addressComponent.district 
        }, () => {
          this.typeList1() //首页游景区
          this.typeList2() //场馆
          this.Venue()
          this.tour()
          wx.request({
            url: 'https://restapi.amap.com/v3/weather/weatherInfo',
            data: {
              'key': '7ccba778f92c5b0b3009c09e1a5a6905', //填入自己申请到的Key
              'city': adcode,
            },
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {

              // 判断显示天气对应的图标
              var weathe = res.data.lives[0].weather
              // console.log(weathe.indexOf('尘')!=-1, "天气预报");
              if (weathe.indexOf('多云') != -1 || weathe.indexOf('阴') != -1 || weathe.indexOf('风') != -1) {
                res.data.lives[0].icon = 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather/yuncai.png'
              } else if (weathe == '晴') {
                res.data.lives[0].icon = 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather/sunshine.png'
              } else if (weathe.indexOf('雪') != -1) {
                res.data.lives[0].icon = 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather/weatherxue.png'
              } else if (weathe.indexOf('雨') != -1 || weathe.indexOf('雹') != -1) {
                res.data.lives[0].icon = 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather/weatheryu.png'
              } else if (weathe.indexOf('雾') != -1 || weathe.indexOf('霾') != -1) {
                res.data.lives[0].icon = 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather/wumai.png'
              } else if (weathe.indexOf('尘') != -1) {
                res.data.lives[0].icon = 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather/fucen.png'
              } else if (weathe.indexOf('雷') != -1) {
                res.data.lives[0].icon = 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather/leidian.png'
              }
              that.setData({
                weather: res.data.lives
              }, () => {

              })
            }
          })
          this.getBenefitsPeopleStoreList(true)
        })
      },
      (err) => {
        // 定位失败回调
        this.setData({
          refreshing: false
        })
      })
  },
  //  公告列表
  gong_Gao() {
    var that = this
    var tempJson = {
      managerId: this.data.managerId,
      pageSize: 10,
      pageNum: 1
    }

    common.getJson('/wlplatfrom/selectAnnouncementListRevision', tempJson, res => {
      if (res.status === 200) {
        for (var i = 0; i < res.data.length; i++) {
          // res.data.itemDesc.replace(/\<img/gi, '<img class="rich-img" ') : ''
          res.data[i].description = res.data[i].description.replace(/\<p>/gi, ' ')
        }
        that.setData({
          gong: res.data
        })

      }
    })
  },

  /**
   * 跳转到对应的分类店铺
   * @param {object} e 点击事件
   */
  toCategoryList(e) {
    const id = e.currentTarget.dataset.item.id
    const storeType = e.currentTarget.dataset.item.storeType
    const name = e.currentTarget.dataset.item.name
    let url = null
    if (id == 6) {
      // 景区景点
      url = '/pages/Dj/ScenicArea/ScenicAreaList/index?type=1&id=' + id + '&managerId=' + this.data.managerId + '&name=' + name + '&storeType=' + storeType + '&fl=lanling'
    } else if (id == 17 || id == 23 || id == 24) {
      // 文化场馆
      url = '/pages/Dj/ScenicArea/ScenicAreaList/index?type=2&id=' + id + '&managerId=' + this.data.managerId + '&name=' + name + '&storeType=' + storeType + '&fl=lanling'
    } else {
      // 店铺
      url = '/pages/Dj/Type/TypeIndex/index?id=' + id + '&managerId=' + this.data.managerId + '&name=' + name + '&storeType=' + storeType + '&fl=lanling'
    }
    wx.navigateTo({
      url
    })
  },
  // 景区跳转
  click_type(e) {
    let {
      id
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/ScenicArea/ScenicAreaMainPage/index?id=' + id + '&moduleType=' + this.data.type,
    })

  },
  // 餐饮
  goodsImgClickss(e) {
    let {
      id
    } = e.currentTarget.dataset

    wx.navigateTo({
      url: '/packageA/pages/activety/activety?id=' + id + '&moduleType=1',
    })
  },
  toGetCoupons() {
    wx.navigateTo({
      url: '/pages/cultureCoupons/index',
    })
  },
  // 首页第二轮播图
  adverList() {
    var that = this
    common.get('/advertisements/firstPageAdsRevision', {
      "managerId": this.data.managerId
    }, res => {
      if (res.status === 200) {
        that.setData({
          tiaoBan: res.data
        })
      } else {
        // common.showRequestErrMsg(res)
      }
    })
  },
  // 首页轮播图两个小方块
  two_ad() {
    var that = this
    var obj = {
      managerId: this.data.managerId,
      module: 3
    }
    common.get('/advertisements/advertisementsRevision', obj, res => {
      if (res.status === 200) {
        that.setData({
          fuckList: res.data
        })
      } else {
        common.showRequestErrMsg(res)
      }
    })
  },
  //获取首页banner图数据
  getBannerInfo() {
    var that = this
    common.getJson('/wlplatfrom/xcx/selectRegionContentListForXcxRevision', {
      "managerId": this.data.managerId
    }, res => {
      if (res.status === 200) {
        this.setData({
          bannerList: res.data
        })
      }
    })
  },
  // 逛场馆
  typeList2() {
    var that = this
    const tempJson = {
      managerId: this.data.managerId,
      storeType: "3",
      userId: "",
    }
    common.post('/wlplatfrom/xcx/selectPageDisposeListRevision ', tempJson, res => {
      // 处理分页数据，每页显示10条
      that.setData({
        tourList3: res.data.slice(0, 3), //品美食
        tourList4: res.data.slice(1, 3)
      })
    })

  },
  // 品美食
  typeList1() {
    var that = this
    const tempJson = {
      managerId: this.data.managerId,
      storeType: "2",
      userId: "",
    }
    common.post('/wlplatfrom/xcx/selectPageDisposeListRevision ', tempJson, res => {
      // 处理分页数据，每页显示10条
      that.setData({
        tourList1: res.data.slice(0, 3), //品美食
        tourList2: res.data.slice(1, 3)
      })
    })

  },
  // 装修分类
  typeList() {
    var that = this
    const tempJson = {
      managerId: this.data.managerId,
      storeType: "1",
      userId: "",
    }
    common.post('/wlplatfrom/xcx/selectPageDisposeListRevision', tempJson, res => {
      that.setData({
        tourList: res.data
      })
    })
  },
  //获取商品分类
  getGoodsType() {
    var that = this
    const tempJson = {
      managerId: this.data.managerId
    }
    common.post('/wlplatfrom/xcx/selectRegionStoreTypeRevision', tempJson, res => {
      // 处理分页数据，每页显示10条
      const list = that.chunkArr(res.data, 10)
      that.setData({
        banner: list,
        bann_ner: res.data
      })
    })
  },
  chunkArr(arr, size) {
    //判断如果不是数组(就没有length)，或者size没有传值，size小于1，就返回空数组 处理轮播下面的
    if (!arr.length || !size || size < 1) return []
    let [start, end, result] = [null, null, []]
    for (let i = 0; i < Math.ceil(arr.length / size); i++) {
      start = i * size
      end = start + size
      result.push(arr.slice(start, end))
    }
    return result
  },

  /**
   * 上拉加载更多
   */
  loadMore() {

    this.getBenefitsPeopleStoreList(false)
  },
  onClickSearch() {
    wx.navigateTo({
      url: '/packageB/pages/search/index'
    })
  },
  // topImgClick() {
  // },
  storeListClick(e) {
    common.gotoStore(e.currentTarget.dataset.item)
  },
  goodsImgClick(e) {
    common.gotoGoodsPage(e.currentTarget.dataset.item)
  },
  chooseLocation() { // 点击选择地理位置
    const that = this
    // const that = this
    wx.chooseLocation({
      success: function (data) {
        let lat = data.latitude //纬
        let lon = data.longitude // 经
        wx.getLocation({ // 这一步 如果用户是首次访问，则会弹出授权弹窗
          type: 'gcj02',
          success: res => {
            const qqmapsdk = new QQMapWX({
              key: 'ONQBZ-CQ4CI-U3EGU-5OWJL-W7PEZ-AEB6X' // 申请的key
            })
            qqmapsdk.reverseGeocoder({
              location: {
                latitude: lat,
                longitude: lon
              },

              success: res => {

                res.result.latitude = lat
                res.result.longitude = lon
                res.result.regeocodeData = {
                  addressComponent: res.result.address_component
                }

                app.cacheLocationData(res.result)
                that.refresh()
              },
              fail: error => {
                Utils.showToast(error.message)
              }
            })

          },
          fail: res => {
            if (res.errMsg == 'getLocation:fail 1' || res.errMsg == 'getLocation:fail system permission denied') {
              // 用户允许授权但获取位置失败，可能有多种原因，比如网络原因、手机系统拒绝使用定位
              //这里写相应的代码
            } else if (res.errMsg == 'getLocation:fail auth deny' || res.errMsg == 'getLocation:fail:auth denied') {
              // 用户拒绝了授权，跳去开启定位页面引导授权的代码
            } else { // 别的错误
              Utils.showToast('网络错误：获取用户所在位置经纬度失败！')
            }
          }
        })

      }
    })
  },
  /**
   * 获取推荐店铺列表好物列表
   * @param {boolean} refresh 是否是刷新数据
   */
  getBenefitsPeopleStoreList(refresh = false) {
    if (this.data.isLoadingBusy) {
      return
    }
    this.setData({
      isLoadingBusy: true
    })
    const pageNum = refresh ? 1 : this.data.pageNum + 1
    const tempJson = {
      regionId: this.data.regionId,
      pageNum,
      pageSize: 10,
      xpoint: this.data.lon,
      ypoint: this.data.lat,
    }
    // 当前是刷新状态，判断标记是否更新  item/cate/listForXcx
    if (refresh && this.data.refreshing === false) {
      this.setData({
        refreshing: true
      })
    }
    // common.post('/wlplatfrom/xcx/store/getSearchStoreList', tempJson, (res) => {
    common.post('/wlplatfrom/item/cate/listForXcx', tempJson, (res) => {
      if (res.status === 200) {
        console.log(res.data, "55663121123333")
        this.data.pageNum = pageNum
        if (!refresh) {
          this.setData({
            benefitListData: [...this.data.benefitListData, ...res.data]
          })
        } else {
          let moreData = true
          if (res.data.length === 0) {
            moreData = false
          }
          this.setData({
            benefitListData: res.data,
            isMore: moreData
          })

        }
        // }
      } else {
        common.showRequestErrMsg(res)
      }
    }, () => {
      this.setData({
        refreshing: false,
        isLoadingBusy: false
      })
    })
  },
  scan() {
    wx.scanCode({
      success: (res) => {
        const result = res.result
        //1. 扫码支付
        if (result && result.indexOf('/pay/scanForPay') != -1) {
          const quary = result.split('?')[1]
          wx.navigateTo({
            url: '/pages/scanForPay/index?' + quary,
          })
        } else {
          common.showToast('暂不支持当前功能~')
        }
      },
      fail: (res) => {
        if (res.errMse != 'scanCode:fail cancel') {
          common.showToast('扫码失败')
        }
      }
    })
  },

  onShareAppMessage: function () {
    return {

      title: '飞羊精选',
      path: '/pages/Dj/index?regionId=' + this.data.regionId,
      imageUrl: 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/xfj/share.jpg',
      success: function (res) {
        // console.log('成功', res)
      }
    }
  },

  adClose() {
    this.setData({
      showAd: false,
    })
  },
  adError(e) {
    this.adClose()
  }
})